package com.oracle.lingshangejia.activity;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.view.View;
import android.widget.CheckBox;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lws.basic.utils.common.AdapterIntegerDefault0;
import com.lws.basic.utils.common.DoubleDefault0Adapter;
import com.oracle.children.ChildrenArchivesActivity;
import com.oracle.lingshangejia.Constant;
import com.oracle.lingshangejia.R;
import com.oracle.lingshangejia.activity.special.ChanHou42MainActivity;
import com.oracle.lingshangejia.activity.special.ChanHouActivity;
import com.oracle.lingshangejia.activity.special.ChanJian25Activity;
import com.oracle.lingshangejia.activity.special.ChanjianArchivesActivity;
import com.oracle.lingshangejia.activity.special.ErTong12ArchivesActivity;
import com.oracle.lingshangejia.activity.special.ErTong18ArchivesActivity;
import com.oracle.lingshangejia.activity.special.ErTong36ArchivesActivity;
import com.oracle.lingshangejia.activity.special.ErTongZhongYiActivity;
import com.oracle.lingshangejia.activity.special.HighBloodPpressureActivity;
import com.oracle.lingshangejia.activity.special.LaoNianRenActivity;
import com.oracle.lingshangejia.activity.special.TangNiaoBingActivity;
import com.oracle.lingshangejia.adapter.VisitRecodeAdapter;
import com.oracle.lingshangejia.bean.DataBean;
import com.oracle.lingshangejia.bean.User;
import com.oracle.lingshangejia.bean.VisitRecordBean;
import com.oracle.lingshangejia.dialog.AddVisitRecordDialog;
import com.oracle.lingshangejia.model.OkgoNetwork;
import com.oracle.lingshangejia.mvp.base.BaseActivity;
import com.oracle.lingshangejia.utils.MyLogger;
import com.oracle.lingshangejia.utils.MyToast;
import com.oracle.lingshangejia.utils.ObserverOnNext;
import com.oracle.lingshangejia.utils.RxUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;


/**
 * 随访记录
 */
public class VisitRecordActivity extends BaseActivity implements BaseQuickAdapter.OnItemChildClickListener,View.OnClickListener, BaseQuickAdapter.OnItemClickListener {
    @BindView(R.id.srl)
    SmartRefreshLayout mSrl;
    @BindView(R.id.rv)
    RecyclerView mRv;
    private VisitRecodeAdapter mAdapter;
    private int mId;
    private int mOffset = 0;
    private int mLimit = 10;


    private void initRecycleview() {
        mRv.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new VisitRecodeAdapter(null);
        mAdapter.setOnItemClickListener(this);
        mAdapter.setOnItemChildClickListener(this);
        mRv.setAdapter(mAdapter);

    }

    @Override
    public int setLayoutId() {
        return R.layout.activity_visitrecode;
    }

    @Override
    public void initData() {
        ButterKnife.bind(this);
        initRecycleview();
        initRefresh();
        mId = getIntent().getIntExtra("id", 0);
        getData();

    }

    private void initRefresh() {
        mSrl.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getData();
            }
        });
        mSrl.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                loadmore();
            }
        });
    }

    private void loadmore() {
        showLoading();
        mOffset += 10;
        Observable.create(new ObservableOnSubscribe<VisitRecordBean>() {
            @Override
            public void subscribe(ObservableEmitter<VisitRecordBean> emitter) throws Exception {
                Map<Object, Object> map = new HashMap<>();
                if (mId != 0) {
                    map.put("grjbxxId", mId);
                }

                map.put("token", User.getToken());
                map.put("mark", 1);
                map.put("offset", mOffset);
                map.put("limit", mLimit);
                map.put("createBy", User.getUserId());
                JSONObject jsonObject = new JSONObject(map);
                MyLogger.i(jsonObject.toString());
                Gson gson = new GsonBuilder()
                        .registerTypeAdapter(Integer.class, new AdapterIntegerDefault0())
                        .registerTypeAdapter(int.class, new AdapterIntegerDefault0())
                        .registerTypeAdapter(Double.class, new DoubleDefault0Adapter())
                        .registerTypeAdapter(double.class, new DoubleDefault0Adapter())
                        .create();
                String json = OkgoNetwork.post(Constant.all_visit_record, jsonObject.toString());
                MyLogger.i(json);
                emitter.onNext(gson.fromJson(json, VisitRecordBean.class));

            }
        }).compose(RxUtils.io_main()).subscribe(new ObserverOnNext<VisitRecordBean>() {
            @Override
            public void onNext(VisitRecordBean bean) {
                if (bean.getMsg().equals("Token已过期")) {
                    startActivity(new Intent(VisitRecordActivity.this, LoginActivity.class));

                } else {
                    if (bean.getData() != null && bean.getData().getRows().size() > 0) {
                        mAdapter.addData(bean.getData().getRows());
                    } else {
                        View emptyView = getLayoutInflater().inflate(R.layout.view_empty, null);
                        mAdapter.setEmptyView(emptyView);
                        MyToast.show("没有随访记录");
                    }
                }
                mSrl.finishLoadmore();
                dismissLoading();
            }
        });
    }


    //获取当前医生随访记录
    private void getData() {
        showLoading();
        mOffset = 0;
        mLimit = 10;
        Observable.create(new ObservableOnSubscribe<VisitRecordBean>() {
            @Override
            public void subscribe(ObservableEmitter<VisitRecordBean> emitter) throws Exception {

                Map<Object, Object> map = new HashMap<>();
                if (mId != 0) {
                    map.put("grjbxxId", mId);
                }
                map.put("token", User.getToken());
                map.put("mark", 1);
                map.put("offset", mOffset);
                map.put("limit", mLimit);
                map.put("createBy", User.getUserId());
                JSONObject jsonObject = new JSONObject(map);
                MyLogger.i(jsonObject.toString());
                Gson gson = new GsonBuilder()
                        .registerTypeAdapter(Integer.class, new AdapterIntegerDefault0())
                        .registerTypeAdapter(int.class, new AdapterIntegerDefault0())
                        .registerTypeAdapter(Double.class, new DoubleDefault0Adapter())
                        .registerTypeAdapter(double.class, new DoubleDefault0Adapter())
                        .create();
                String json = OkgoNetwork.post(Constant.all_visit_record, jsonObject.toString());
                MyLogger.i(json);
                emitter.onNext(gson.fromJson(json, VisitRecordBean.class));

            }
        }).compose(RxUtils.io_main()).subscribe(new ObserverOnNext<VisitRecordBean>() {
            @Override
            public void onNext(VisitRecordBean bean) {
                if (bean.getMsg().equals("Token已过期")) {
                    startActivity(new Intent(VisitRecordActivity.this, LoginActivity.class));
                    finish();
                } else {
                    if (bean.getData() != null && bean.getData().getRows().size() > 0) {
                        mAdapter.setNewData(bean.getData().getRows());
                    } else {
                        View emptyView = getLayoutInflater().inflate(R.layout.view_empty, null);
                        mAdapter.setEmptyView(emptyView);
                        mAdapter.setNewData(null);
                        MyToast.show("没有随访记录");
                    }
                }
                dismissLoading();
                mSrl.finishRefresh();
            }
        });


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ib_back:  //返回
                finish();
                break;
            case R.id.ib_list:  //添加随访记录
                AddVisitRecordDialog dialog = new AddVisitRecordDialog();
                dialog.show(getSupportFragmentManager(), "");
                break;
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        List<VisitRecordBean.DataBean.RowsBean> list = (List<VisitRecordBean.DataBean.RowsBean>) mAdapter.getData();
        Intent intent = new Intent();
        intent.putExtra("jmid", list.get(position).getGrjbxxId());
        intent.putExtra("id", list.get(position).getId());
        if (list.get(position).getSfResult()==7){
                MyToast.show("该随访任务已经完成");
        }else {
            switch (list.get(position).getZxName()) {
                case "新生儿家庭访视记录":
                    intent.setClass(this, ChildrenArchivesActivity.class);
                    break;
                case "高血压患者随访记录":
                    intent.setClass(this, HighBloodPpressureActivity.class);
                    break;
                case "2型糖尿病患者健康随访记录":
                    intent.setClass(this, TangNiaoBingActivity.class);
                    break;
                case "老年人中医药健康管理":
                    intent.setClass(this, LaoNianRenActivity.class);
                    break;
                case "1到8月龄儿童健康检查记录":
                    intent.setClass(this, ErTong18ArchivesActivity.class);
                    break;
                case "12到30月龄儿童健康检查记录":
                    intent.setClass(this, ErTong12ArchivesActivity.class);
                    break;
                case "3到6岁儿童健康检查记录":
                    intent.setClass(this, ErTong36ArchivesActivity.class);
                    break;
                case "儿童中医药健康管理服务记录":
                    intent.setClass(this, ErTongZhongYiActivity.class);
                    break;
                case "孕产妇一次产前检查记录":
                    intent.setClass(this, ChanjianArchivesActivity.class);
                    break;
                case "孕产妇2到5次产前随访服务记录":
                    intent.setClass(this, ChanJian25Activity.class);
                    break;
                case "孕产妇产后访视记录":
                    intent.setClass(this, ChanHouActivity.class);
                    break;
                case "孕产妇产后42天健康检查记录":
                    intent.setClass(this, ChanHou42MainActivity.class);
                    break;
                case "健康体检表":
                    intent.setClass(this, HealthCheckArchivesActivity.class);
                    break;


            }
            startActivity(intent);
        }


    }

    @OnClick({R.id.iv_app_push, R.id.iv_postpone})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_app_push://推送
                new MaterialDialog.Builder(this)
                        .title("app通知下发")
                        .content("是否给居民发消息")
                        .positiveText("确认")
                        .negativeText("取消")
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(MaterialDialog dialog, DialogAction which) {
                                Observable.create(new ObservableOnSubscribe<DataBean>() {
                                    @Override
                                    public void subscribe(ObservableEmitter<DataBean> emitter) throws Exception {
                                        showLoading();
                                        List<Integer> list =new ArrayList<>();
                                        for (VisitRecordBean.DataBean.RowsBean rowsBean:mAdapter.getData()){

                                            if (rowsBean.isIs()){
                                                MyLogger.i(rowsBean.getId()+"");
                                                list.add(rowsBean.getId());
                                            }
                                        }
                                        Map<Object, Object> map = new HashMap<>();
                                        map.put("token", User.getToken());
                                        map.put("mark", 1);
                                        map.put("sfjlids",list);
                                        JSONObject jsonObject = new JSONObject(map);
                                        MyLogger.i(jsonObject.toString());
                                        String json = OkgoNetwork.post(Constant.app_push, jsonObject.toString());
                                        Gson gson = new Gson();
                                        emitter.onNext(gson.fromJson(json, DataBean.class));


                                    }
                                }).compose(RxUtils.io_main()).subscribe(new ObserverOnNext<DataBean>() {
                                    @Override
                                    public void onNext(DataBean dataBean) {
                                        dismissLoading();
                                        if (dataBean.getCode()==0){
                                            MyToast.show("发送成功");
                                            getData();
                                        }else {
                                            MyToast.show(dataBean.getMsg());
                                        }


                                        dialog.dismiss();
                                    }
                                });
                            }
                        })
                        .onNeutral(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(MaterialDialog dialog, DialogAction which) {
                                dialog.dismiss();
                            }
                        })
                        .show();
                break;
            case R.id.iv_postpone://延期

                new MaterialDialog.Builder(this)
                        .title("延期")
                        .content("")
                        .inputType(InputType.TYPE_CLASS_NUMBER)
                        .input("请输入天数", null, new MaterialDialog.InputCallback() {
                            @Override
                            public void onInput(MaterialDialog dialog, CharSequence input) {
                                Observable.create(new ObservableOnSubscribe<DataBean>() {
                                    @Override
                                    public void subscribe(ObservableEmitter<DataBean> emitter) throws Exception {
                                        showLoading();
                                        List<Integer> list =new ArrayList<>();
                                        for (VisitRecordBean.DataBean.RowsBean rowsBean:mAdapter.getData()){
                                            if (rowsBean.isIs()){
                                                list.add(rowsBean.getId());
                                            }
                                        }
                                        Map<Object, Object> map = new HashMap<>();
                                        map.put("token", User.getToken());
                                        map.put("mark", 1);
                                        map.put("sfjlids",list);
                                        map.put("days", Integer.valueOf(input.toString()));
                                        JSONObject jsonObject = new JSONObject(map);
                                        MyLogger.i(jsonObject.toString());
                                        String json = OkgoNetwork.post(Constant.postpone, jsonObject.toString());
                                        Gson gson = new Gson();
                                        emitter.onNext(gson.fromJson(json, DataBean.class));


                                    }
                                }).compose(RxUtils.io_main()).subscribe(new ObserverOnNext<DataBean>() {
                                    @Override
                                    public void onNext(DataBean dataBean) {
                                        dismissLoading();
                                        if (dataBean.getCode()==0){
                                            getData();
                                            MyToast.show("延期成功");
                                        }else {
                                            MyToast.show(dataBean.getMsg());
                                        }


                                        dialog.dismiss();
                                    }
                                });
                            }
                        })
                        .positiveText("确定")
                        .show();


                break;
        }
    }


    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

        if (((CheckBox)view).isChecked()){
            mAdapter.getData().get(position).setIs(true);
        }else {
            mAdapter.getData().get(position).setIs(false);
        }
    }
}
